﻿/*
 * 配置文件类，具有缓存及缓存自动更新机制。
 * 通过AppSettings的ConfigFile配置指定配置文件路径
 * 自动监视文件修改，及时更新缓存。
 */


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Configuration;
using System.Xml;
namespace HZ
{
    /// <summary>
    /// 配置文件类，具有缓存及缓存自动更新机制。
    /// </summary>
    public class ConfigManager
    {
        static string filename;
        public static FileSystemWatcher watcher = new FileSystemWatcher();
        static NameValueCollection appsettings;
        static ConfigManager()
        {
            RefreshConfig();
        }
        static void RefreshConfig()
        {
            filename = ConfigurationManager.AppSettings["ConfigFile"];
            // 没有配置文件直接返回
            if (filename == null)
            {
                return;
            }
            watcher.Filter = "*" + Path.GetExtension(filename);
            if (System.Web.HttpContext.Current == null)
            {
                watcher.Path = Environment.CurrentDirectory;
                filename = watcher.Path + "\\" + filename;
            }
            else
            {
                watcher.Path = System.Web.HttpContext.Current.Server.MapPath("~/");
                filename = watcher.Path + filename;
            }

            watcher.NotifyFilter = NotifyFilters.LastWrite;

            watcher.Changed += new FileSystemEventHandler(Changed);
            // Begin watching.
            watcher.EnableRaisingEvents = true;

            appsettings = GetConfig(filename);
        }

        static void Changed(object sender, FileSystemEventArgs e)
        {
            System.Threading.Thread.Sleep(1000); //休眠1秒。
            appsettings.Clear();
            appsettings = GetConfig(filename);
        }

        static NameValueCollection GetConfig(string file)
        {
            NameValueCollection result = new NameValueCollection();
            XmlTextReader reader;
            try
            {
                reader = new XmlTextReader(file);
            }
            catch
            {
                throw new System.IO.IOException("配置文件路径错误");
            }
            reader.WhitespaceHandling = WhitespaceHandling.None;
            result.Clear();

            while (reader.Read())
            {
                if (reader.Name == "add")
                {
                    string key, value;
                    reader.MoveToAttribute("key"); key = reader.Value;
                    reader.MoveToAttribute("value"); value = reader.Value;
                    result.Add(key, value);
                }
            }
            reader.Close();
            return result;
        }

        public static NameValueCollection AppSettings
        {
            get { return appsettings; }
        }
    }
}
